<template>
    <!-- <el-form label-width="110px" size="small">
        <el-col class="form-row"> -->
    <div>
        <el-form-item label="价格模式:" v-if="!notShowPriceType">
            <el-select v-model="form.orderPriceType" size="mini" disabled>
                <el-option v-for="i in investPriceSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                </el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="当前市价:" :class="['font-color-' + textColor]" class="icon-form-item">
            <el-input v-model="calcPrice" disabled>
                <template slot="append">元</template>
            </el-input>
            <i v-if="!notShowPriceType" class="el-icon-refresh-right" @click="getCalcPrice('1')"></i>
        </el-form-item>
        <el-form-item v-if="isNetPrice" label="净价价格:">
            <RiskInputNumber
                :input="form.netPrice"
                :inputAfter="'元'"
                :colorStyle="textColor"
                :precision="2"
                :maxlength="10"
                :field="'netPrice'"
                :disabled="!checkPermission('B_325') || ['A', 'T', 'U'].includes(orderDirection)"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item v-else label="全价价格:">
            <RiskInputNumber
                :input="form.allPrice"
                :inputAfter="'元'"
                :colorStyle="textColor"
                :precision="2"
                :maxlength="10"
                :field="'allPrice'"
                :disabled="!checkPermission('B_325') || ['A', 'T', 'U'].includes(orderDirection)"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item :label="isNetPrice ? '指令数量:' : '全价数量:'">
            <RiskInputNumber
                :input="form.orderAmount"
                :inputAfter="'张'"
                :colorStyle="textColor"
                :maxlength="12"
                :precision="2"
                :readonly="!stockCode"
                :field="'orderAmount'"
                :disabled="targetType == '2'"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item v-if="isNetPrice" label="净价金额:">
            <RiskInputNumber
                :input="form.netMoney"
                :inputAfter="'元'"
                :colorStyle="textColor"
                :precision="2"
                :field="'netMoney'"
                :maxlength="12"
                :disabled="balanceDisabledStatus"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item v-else label="全价金额:">
            <RiskInputNumber
                :input="form.allMoney"
                :inputAfter="'元'"
                :colorStyle="textColor"
                :precision="2"
                :maxlength="12"
                :field="'allMoney'"
                :disabled="balanceDisabledStatus"
                @getInputNumber="getInputNumber(arguments)"
            >
            </RiskInputNumber>
        </el-form-item>
        <el-form-item label="预估中签率:" v-if="buyBond">
            <RiskInputNumber :input="winningRate" :inputAfter="'%'" :maxlength="7" :field="'winningRate'" @getInputNumber="getInputNumber(arguments)">
            </RiskInputNumber>
        </el-form-item>
        <!-- </el-col>
    </el-form> -->
    </div>
</template>
<script lang="ts">
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SGU_CACHE } from '@/utils/diction-const-util';
import { checkPermission, convertNum, handleInverseAmount, handleLimitAmount } from '@/utils/tools';

@Component({
    name: 'BondForm',
    components: {
        RiskInputNumber,
    },
})
// 债券指令额外表单
export default class BondForm extends Vue {
    @Prop()
    formDetail: any;
    @Prop()
    buyBond: boolean; // 是否申购债券
    @Prop()
    isNetPrice: boolean; // 是否净价
    @Prop()
    stockInfo: any;
    @Prop()
    stockCode: string;
    @Prop()
    orderDirection: string; // 委托方向
    @Prop()
    textColor: string;
    @Prop()
    notMesh: boolean; // 非风险试算页面
    @Prop()
    notShowPriceType: boolean; // 是否显示价格模式(不同页面使用该组件用到该变量)
    @Prop()
    targetType: string; // 目标类型
    @Prop()
    refreshNumber: number;
    @Prop()
    changeFlag: string;
    checkPermission = checkPermission;

    form = {
        // businessType: '',
        netPrice: '', // 净价价格
        orderAmount: '', // 指令数量
        netMoney: '', // 指令金额
        allPrice: '', // 全价价格
        allMoney: '', // 全价金额
        winningRate: '', // 预估中签率
        orderPriceType: '2', // 价格模式
    };

    calcPrice: number = 0;
    winningRate: string = '';
    netPrice: string = '';
    allPrice: string = '';
    investPriceSelectData: any[] = []; // 价格模式下拉数据

    @Watch('stockInfo.stockCode', { immediate: true, deep: true })
    onWacthStockCode(newValue, oldValue) {
        if (oldValue) {
            this.resetForm();
        }
        this.getCalcPrice('2');
    }

    @Watch('refreshNumber', { immediate: true })
    onWatchRefreshNumber() {
        if (this.refreshNumber) {
            this.getCalcPrice('2');
        }
    }

    /**
     * 获取指令价格为空时的计算价格，下面是取值顺序
     * lastPrice: 最新价
     * openPrice: 开盘价
     * closePrice: 昨收盘价
     * facePrice: 面值
     * type: 1-手动刷新(点击刷新图标)，2-自动刷新(切换证券时)
     */
    getCalcPrice(type: string) {
        if (this.stockCode) {
            this.$axios
                .post('/dataEngine/getStockPrice/' + this.stockCode)
                .then((result: any) => {
                    this.calcPrice = result;
                    if (this.form.orderPriceType == '2') {
                        this.handlePriceChange('');
                    }
                    if (type == '1') {
                        this.yh_message_success('刷新成功');
                    }
                })
                .catch(() => {
                    this.calcPrice = null;
                });
        } else {
            this.calcPrice = null;
        }
    }

    @Watch('orderDirection', { immediate: true, deep: true })
    onWatchOrderDirection(newValue, oldValue) {
        if (this.orderDirection == 'A' || (['U', 'T'].includes(oldValue) && !['U', 'T'].includes(newValue))) {
            if (this.isNetPrice) {
                this.form.netPrice = '';
            } else {
                this.form.allPrice = '';
            }
            this.form.orderPriceType = '2';
        } else if (['U', 'T'].includes(this.orderDirection)) {
            if (this.isNetPrice) {
                this.form.netPrice = '1';
            } else {
                this.form.allPrice = '1';
            }
            this.form.orderPriceType = '1';
        }

        if (this.form.orderAmount) {
            this.handleOrderMountChange(this.form.orderAmount);
        }
    }

    @Watch('form', { immediate: true, deep: true })
    setForm(newValue, oldValue) {
        this.$emit(
            'getForm',
            {
                netPrice: this.netPrice, // 净价价格
                orderAmount: this.form.orderAmount, // 指令数量
                netMoney: this.form.netMoney, // 指令金额
                allPrice: this.allPrice, // 全价价格
                allMoney: this.form.allMoney, // 全价金额
                winningRate: this.form.winningRate, // 预估中签率
                orderPriceType: this.form.orderPriceType, // 价格类型
            },
            'bondValues'
        );
    }

    @Watch('formDetail', { immediate: true, deep: true })
    getForm() {
        for (const key in this.formDetail) {
            this.form[key] = this.formDetail[key];
        }
        if (this.formDetail.orderPriceType === '2') {
            if (this.formDetail.allPrice) {
                this.form.allPrice = '';
                this.allPrice = this.formDetail.allPrice;
            } else if (this.formDetail.netPrice) {
                this.form.netPrice = '';
                this.netPrice = this.formDetail.netPrice;
            }
        }
        if (this.form.winningRate) {
            this.winningRate = (Number(this.form.winningRate) * 100).toString();
        }
    }

    @Watch('changeFlag', { immediate: true, deep: true })
    onWatchChangeFlag() {
        if (this.form.orderAmount) {
            if (this.form.orderAmount === '0.00') {
                this.yh_message_warn('指令数量必须大于0！');
                return;
            }
            let limit = handleLimitAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
            if (!limit) {
                this.form.orderAmount = '';
            }
        }
    }

    async mounted() {
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
    }

    get balanceDisabledStatus() {
        if (this.targetType == '1') {
            return true;
        } else {
            return false;
        }
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        if (field !== 'winningRate') {
            this.form[field] = value;
        } else if (value) {
            this.form.winningRate = (Number(value) / 100).toString();
        }
        if (field === 'netPrice' || field === 'allPrice') {
            this.handlePriceChange(value);
        } else if (field === 'orderAmount') {
            this.handleOrderMountChange(value);
        } else if (field === 'netMoney' || field === 'allMoney') {
            this.handleOrderBalanceChange(value);
        }
    }

    handleOrderBalanceChange(value: string) {
        let orderPrice: string = '';
        if (this.isNetPrice) {
            orderPrice = this.netPrice;
        } else {
            orderPrice = this.allPrice;
        }
        if (orderPrice) {
            this.form.orderAmount = (Number(value || '0') / Number(orderPrice || '0')).toFixed(0);
        } else {
            if (this.calcPrice) {
                this.form.orderAmount = (Number(value || '0') / this.calcPrice).toFixed(0);
            }
        }

        // 反算指令数量处理
        this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
    }

    handlePriceChange(value: string) {
        // 修改指令价格
        if (value) {
            // 根据输入值计算
            this.form.orderPriceType = '1';
        } else {
            this.form.orderPriceType = '2';
        }
        this.calAmountOrBalance(this.form);
    }

    handleOrderMountChange(val: any) {
        if (val === '0.00') {
            this.yh_message_warn('指令数量必须大于0！');
            this.form.orderAmount = '';
            return;
        }
        let limit = handleLimitAmount(this.changeFlag, this.stockInfo, val);
        if (!limit) {
            this.form.orderAmount = '';
        }
        // 当委托方向为A-转股时, 指令金额=指令数量*当前面值
        if (this.orderDirection === 'A') {
            if (this.isNetPrice) {
                this.netPrice = this.stockInfo?.facePrice;
                this.form.netMoney = (Number(this.netPrice || 0) * Number(this.form.orderAmount || 0)).toFixed(2);
            } else {
                this.allPrice = this.stockInfo?.facePrice;
                this.form.allMoney = (Number(this.allPrice || 0) * Number(this.form.orderAmount || 0)).toFixed(2);
            }
        } else {
            this.calNetPriceOrAllPrice(this.form);
        }
    }

    /**
     * 计算数量或金额
     */
    calAmountOrBalance(form) {
        // 当委托方向为A-转股时, 指令金额=指令数量*当前面值
        if (this.orderDirection === 'A') {
            if (this.isNetPrice) {
                this.netPrice = this.stockInfo?.facePrice;
            } else {
                this.allPrice = this.stockInfo?.facePrice;
            }
        }
        // 是否净价
        if (this.isNetPrice) {
            // 限价
            if (form.orderPriceType === '1') {
                this.netPrice = this.form.netPrice;
                if (this.targetType == '1') {
                    if (this.form.orderAmount) {
                        // 绝对数量算金额
                        form.netMoney = (Number(this.form.orderAmount || '0') * Number(this.netPrice || '0')).toFixed(2);
                        form.netMoney = this.handleVerifyOrderBlance(form.netMoney);
                    }
                } else if (this.targetType == '2') {
                    if (form.netMoney) {
                        // 绝对金额反推数量
                        this.form.orderAmount = (Number(form.netMoney || '0') / Number(this.netPrice)).toFixed(2);
                        // 反算指令数量处理
                        this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                    }
                }
                // if (form.netMoney) {
                //     form.netMoney = (Number(this.form.orderAmount || '0') * Number(this.netPrice || '0')).toFixed(2);
                //     form.netMoney = this.handleVerifyOrderBlance(form.netMoney);
                // } else if (this.form.orderAmount) {
                //     // 如果没有金额只有数量，计算金额就行
                //     form.netMoney = (Number(this.form.orderAmount || '0') * Number(this.netPrice || '0')).toFixed(2);
                //     form.netMoney = this.handleVerifyOrderBlance(form.netMoney);
                // } else {
                //     // 金额数量都是空，不做处理
                // }
            } else {
                if (this.calcPrice == null) {
                    this.netPrice = '';
                } else {
                    this.netPrice = this.calcPrice.toString();
                }
                if (this.calcPrice) {
                    this.netPrice = this.calcPrice.toString();
                    if (form.netMoney) {
                        if (this.targetType == '1') {
                            // 绝对数量算金额
                            form.netMoney = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                            form.netMoney = this.handleVerifyOrderBlance(form.netMoney);
                        } else if (this.targetType == '2') {
                            // 绝对金额反推数量
                            this.form.orderAmount = (Number(form.netMoney || '0') / Number(this.calcPrice || '0')).toFixed(0);
                            this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                            // if (this.form.orderAmount === '') {
                            //     form.netMoney = '';
                            // }
                        }
                    } else if (this.form.orderAmount) {
                        if (this.targetType == '1') {
                            // 如果没有金额只有数量，计算金额就行
                            form.netMoney = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                            form.netMoney = this.handleVerifyOrderBlance(form.netMoney);
                        }
                    } else if (this.targetType == '2') {
                    } else {
                        // 金额数量都是空，不做处理
                    }
                }
            }
        } else {
            // 限价
            if (form.orderPriceType === '1') {
                this.allPrice = this.form.allPrice;
                if (this.targetType == '1') {
                    if (this.form.orderAmount) {
                        // 绝对数量算金额
                        form.allMoney = (Number(this.form.orderAmount || '0') * Number(this.allPrice || '0')).toFixed(2);
                        form.allMoney = this.handleVerifyOrderBlance(form.allMoney);
                    }
                } else if (this.targetType == '2') {
                    if (form.allMoney) {
                        // 绝对金额反推数量
                        this.form.orderAmount = (Number(form.allMoney || '0') / Number(this.allPrice)).toFixed(2);
                        console.log(form.allMoney, this.allPrice, this.form.orderAmount, ' this.form.orderAmount');

                        // 反算指令数量处理
                        this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                    }
                }
                // if (form.allMoney) {
                //     form.allMoney = (Number(this.form.orderAmount || '0') * Number(this.allPrice || '0')).toFixed(2);
                //     form.allMoney = this.handleVerifyOrderBlance(form.allMoney);
                // } else if (this.form.orderAmount) {
                //     // 如果没有金额只有数量，计算金额就行
                //     form.allMoney = (Number(this.form.orderAmount || '0') * Number(this.allPrice || '0')).toFixed(2);
                //     form.allMoney = this.handleVerifyOrderBlance(form.allMoney);
                // } else {
                //     // 金额数量都是空，不做处理
                // }
            } else {
                if (this.calcPrice == null) {
                    this.allPrice = '';
                } else {
                    this.allPrice = this.calcPrice.toString();
                }
                if (this.calcPrice) {
                    // this.allPrice = this.calcPrice.toString();
                    if (form.allMoney) {
                        if (this.targetType == '1') {
                            // 绝对数量算金额
                            form.allMoney = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                            form.allMoney = this.handleVerifyOrderBlance(form.allMoney);
                        } else if (this.targetType == '2') {
                            // 绝对金额反推数量
                            this.form.orderAmount = (Number(form.allMoney || '0') / Number(this.calcPrice || '0')).toFixed(0);
                            this.form.orderAmount = handleInverseAmount(this.changeFlag, this.stockInfo, this.form.orderAmount);
                            if (this.form.orderAmount === '') {
                                form.allMoney = '';
                            }
                            // this.form.orderAmount = handleInverseAmount(this.textColor, this.stockInfo, this.form.orderAmount);
                        }
                    } else if (this.form.orderAmount) {
                        if (this.targetType == '1') {
                            // 如果没有金额只有数量，计算金额就行
                            form.allMoney = (Number(this.form.orderAmount || '0') * Number(this.calcPrice || '0')).toFixed(2);
                            form.allMoney = this.handleVerifyOrderBlance(form.allMoney);
                        } else if (this.targetType == '2') {
                        }
                    } else {
                        // 金额数量都是空，不做处理
                    }
                }
            }
        }
    }

    // 计算净价或全价金额
    calNetPriceOrAllPrice(form) {
        let orderBalance: string = '';
        // 是否净价
        if (this.isNetPrice) {
            // 限价
            if (form.orderPriceType === '1') {
                orderBalance = (Number(form.netPrice || 0) * Number(form.orderAmount || 0)).toFixed(2);
                this.netPrice = this.form.netPrice;
            } else {
                orderBalance = (Number(this.calcPrice || 0) * Number(form.orderAmount || 0)).toFixed(2);
                if (this.calcPrice == null) {
                    this.netPrice = '';
                } else {
                    this.netPrice = this.calcPrice.toString();
                }
            }
            if (convertNum(orderBalance) === false || Number(orderBalance) > 999999999999.99) {
                this.yh_message_warn('净价金额不能超过999999999999.99!');
                orderBalance = '';
            }
            form.netMoney = orderBalance;
        } else {
            if (form.orderPriceType === '1') {
                orderBalance = (Number(form.allPrice || 0) * Number(form.orderAmount || 0)).toFixed(2);
                this.allPrice = this.form.allPrice;
            } else {
                orderBalance = (Number(this.calcPrice || 0) * Number(form.orderAmount || 0)).toFixed(2);
                // this.allPrice = this.calcPrice.toString();
                if (this.calcPrice == null) {
                    this.allPrice = '';
                } else {
                    this.allPrice = this.calcPrice.toString();
                }
            }
            if (convertNum(orderBalance) === false || Number(orderBalance) > 999999999999.99) {
                this.yh_message_warn('全价金额不能超过999999999999.99!');
                orderBalance = '';
            }
            form.allMoney = orderBalance;
        }
    }

    // 校验指令金额
    handleVerifyOrderBlance(orderBalance: any) {
        if (convertNum(orderBalance) === false || Number(orderBalance) > 999999999999.99) {
            this.yh_message_warn('指令金额不能超过999999999999.99!');
            orderBalance = '';
        }
        return orderBalance;
    }

    // 重置表单
    resetForm() {
        this.form.netPrice = '';
        this.form.orderAmount = '';
        this.form.netMoney = '';
        this.form.allPrice = '';
        this.form.allMoney = '';
        this.form.winningRate = '';
        this.form.orderPriceType = '2';
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-time/styles/order-form';
</style>
